<!--  -->
<template>
    <div class='main' >
        <div>忘记密码</div>
        <a-form
            id="formLogin"
            class="user-layout-login"
            ref="formLogin"
            :form="form"
            @submit="handleSubmit"
        >
            <a-form-item>
                <a-input
                    size="large"
                    type="text"
                    :placeholder="'请输入手机号'"
                    v-decorator="[
                        'phone',
                        {rules: [{ required: true, pattern: /^1[3456789]\d{9}$/, message: '请输入账号' }], validateTrigger: 'change'}
                    ]"
                    >
                    <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
            </a-form-item>

            <a-row :gutter="16">
                <a-col class="gutter-row" :span="16">
                <a-form-item>
                    <a-input size="large" type="text" :placeholder="$t('user.login.mobile.verification-code.placeholder')" v-decorator="['verifyCode', {rules: [{ required: true, message: $t('user.verification-code.required') }], validateTrigger: 'blur'}]">
                    <a-icon slot="prefix" type="safety" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                    </a-input>
                </a-form-item>
                </a-col>
                <a-col class="gutter-row" :span="8">
                <a-button
                    class="getCaptcha"
                    tabindex="-1"
                    :disabled="state.smsSendBtn"
                    @click.stop.prevent="getCaptcha"
                    v-text="!state.smsSendBtn && $t('user.register.get-verification-code') || (state.time+' s')"
                ></a-button>
                </a-col>
            </a-row>

            <a-form-item>
                <a-input-password
                    size="large"
                    :placeholder="$t('user.login.password.placeholder')"
                    v-decorator="[
                        'password',
                        {rules: [{ required: true, message: $t('user.password.required') }, { validator: this.handlePasswordLevel}], validateTrigger: ['blur','change']}
                    ]"
                    >
                    <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input-password>
            </a-form-item>
            <a-form-item>
                <a-input-password
                    size="large"
                    :placeholder="'请再次输入密码'"
                    v-decorator="[
                        'confirmPassword',
                        {rules: [{ required: true, message: $t('user.password.required') }, { validator: this.handlePasswordCheck}], validateTrigger: ['blur']}
                    ]"
                    >
                    <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input-password>
            </a-form-item>

            <a-form-item>
                <router-link
                :to="{ name: 'login', params: { user: 'aaa'} }"
                class="forge-password"
                >密码登录</router-link>
                <router-link class="register" style="float: right;" :to="{ name: 'phoneLogin' }">验证码登录</router-link>
            </a-form-item>

            <a-form-item style="margin-top:24px">
                <a-button
                size="large"
                type="primary"
                htmlType="submit"
                class="login-button"
                :loading="state.loginBtn"
                :disabled="state.loginBtn"
                >确认修改</a-button>
            </a-form-item>
        </a-form>
    </div>
</template>

<script>
import { getSmsCaptcha } from '@/api/login';
import { updateUserPassword } from '@/api/system';
import { scorePassword } from '@/utils/util'
export default {
    data () {
        return {
            form: this.$form.createForm(this),
            state: {
                time: 60,
                loginBtn: false,
                loginType: 0,
                smsSendBtn: false
            },
        };
    },

    methods: {
        handleSubmit (e) {
            e.preventDefault()
            const {
                form: { validateFields },
                state,
                Login
            } = this

            state.loginBtn = true

            const validateFieldsKey = ['phone', 'verifyCode','password','confirmPassword'];

            validateFields(validateFieldsKey, { force: true }, (err, values) => {
                if (!err) {
                console.log('login form', values)
                const loginParams = { ...values }
                updateUserPassword(loginParams)
                    .then((res) => {
                        if(res.success){
                            this.$notification['success']({
                                message: '温馨提示',
                                description: '密码修改成功',
                                duration: 4
                            })
                            this.$router.push({name: 'login'})
                        }else{
                            this.$notification['error']({
                                message: '温馨提示',
                                description: res.errMessage,
                                duration: 4
                            })
                        }
                    })
                    .catch(err => this.requestFailed(err))
                    .finally(() => {
                    state.loginBtn = false
                    })
                } else {
                setTimeout(() => {
                    state.loginBtn = false
                }, 600)
                }
            })
        },
        handlePasswordLevel (rule, value, callback) {
            if (!value) {
                return callback()
            }
            console.log('scorePassword ; ', scorePassword(value))
            if (value.length >= 6 && value.length <= 20) {
                if (scorePassword(value) >= 30) {
                this.state.level = 1
                }
                if (scorePassword(value) >= 60) {
                this.state.level = 2
                }
                if (scorePassword(value) >= 80) {
                this.state.level = 3
                }
            } else if(value.length > 20){
                this.state.level = 0
                callback(new Error('密码长度不能超过20个字符'))
            } else {
                this.state.level = 0
                callback(new Error(this.$t('user.password.strength.msg')))
            }
            this.state.passwordLevel = this.state.level
            this.state.percent = this.state.level * 33
            callback()
        },
        handlePasswordCheck (rule, value, callback) {
            const password = this.form.getFieldValue('password')
            // console.log('value', value)
            if (value === undefined) {
                callback(new Error(this.$t('user.password.required')))
            }
            if (value && password && value.trim() !== password.trim()) {
                callback(new Error(this.$t('user.password.twice.msg')))
            }
            callback()
        },
        getCaptcha (e) {
            e.preventDefault()
            const { form: { validateFields }, state } = this

            validateFields(['phone'], { force: true }, (err, values) => {
                if (!err) {
                state.smsSendBtn = true

                const interval = window.setInterval(() => {
                    if (state.time-- <= 0) {
                    state.time = 60
                    state.smsSendBtn = false
                    window.clearInterval(interval)
                    }
                }, 1000)

                const hide = this.$message.loading('验证码发送中..', 0)
                getSmsCaptcha({ phone: values.phone , businessType: 'FORGET_PASSWORD'}).then(res => {
                    setTimeout(hide, 2500)
                    if(res.success){
                    this.$notification['success']({
                        message: '提示',
                        description: `验证码已发送至尾号${values.phone.substring(7)}上，请注意查收`,
                        duration: 8
                    })
                    }else{
                    this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8
                    })
                    }
                }).catch(err => {
                    setTimeout(hide, 1)
                    clearInterval(interval)
                    state.time = 60
                    state.smsSendBtn = false
                    this.requestFailed(err)
                })
                }
            })
        },
        requestFailed (err) {
            console.log(err,'err')
            this.isLoginError = true
            this.$notification['error']({
                message: '错误',
                description: err || '请求出现错误，请稍后再试',
                duration: 4
            })
        }
    }
}

</script>
<style lang="less" scoped>
.user-layout-login {
    label {
        font-size: 14px;
    }

    .getCaptcha {
        display: block;
        width: 100%;
        height: 40px;
    }

    .forge-password {
        font-size: 14px;
    }

    button.login-button {
        padding: 0 15px;
        font-size: 16px;
        height: 40px;
        width: 100%;
    }

    .user-login-other {
        text-align: left;
        margin-top: 24px;
        line-height: 22px;

        .item-icon {
            font-size: 24px;
            color: rgba(0, 0, 0, 0.2);
            margin-left: 16px;
            vertical-align: middle;
            cursor: pointer;
            transition: color 0.3s;
            &:hover {
                color: #1890ff;
            }
        }

        .register {
            float: right;
        }
    }
}
</style>